<template>
    <!-- {{ state.fileIsArray }} -->
    <a-upload v-model:file-list="state.fileList" list-type="picture-card"
        @preview="handlePreview" @change="handleChangeImport" :customRequest="customRequest" accept=".png,.jpg,.jpeg"
        :maxCount="maxCount" :before-upload="beforeUpload" :disabled="disabled">
        <div>
            <PlusOutlined style="color: #999;" />
            <div style="margin-top: 8px;color: #999">点击上传图片</div>
        </div>
    </a-upload>
    <!-- 提示问本插槽 -->
    <div class="uptile">
        <slot name="tip"></slot>
    </div>
    <!-- <div class="uptile">标题图片格式为jpg或png，宽300px*高300px，不得超过300KB</div> -->
    <a-modal :visible="state.previewVisible" title="图片预览" :footer="null" @cancel="state.previewVisible = false">
        <img alt="example" style="width: 100%" :src="state.previewImage" />
    </a-modal>
</template>

<script setup>
import { reactive, ref, onMounted, watch, onActivated, defineEmits } from 'vue';
import { EditOutlined, GlobalOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { fileUpload } from '@/service/api'
// import { uploadFn } from '@/service/api'
import { message, Upload } from "ant-design-vue";
const emit = defineEmits(['change', 'updateFiles'])

const props = defineProps({
    // 最大上传数量
    maxCount: {
        default: () => 1,
        type: Number
    },
    // 上传文件 可以为字符串 也可以为数组
    files: {
        default: () => '',
        type: [String, Array],
    },

    // 最大上传尺寸  kb计数
    maxSize: {
        default: () => 1024,
        type: Number
    },
    // 最小上传宽度
    minWidth: {
        default: () => 0,
        type: Number
    },
    // 最小上传高度
    minHeight: {
        default: () => 0,
        type: Number
    },
    // 严格宽度
    strictWidth: {
        default: () => 0,
        type: Number
    },
    // 严格高度
    strictHeight: {
        default: () => 0,
        type: Number
    },

    // 是否禁用
    disabled: {
        default: () => false,
        type: Boolean
    },

    // imgSizeType: {
    //     default: () => '1',
    //     type: String
    // },
})
let state = reactive({


    fileList: [],
    previewVisible: false,
    previewImage: '',

    fileIsArray: false,
    // imgUrl: [],  //图片

    // mapPosition:[]
})
watch(

    () => props.files,

    (value) => {
        if (!value) {
            state.fileList = []
        } else {


            // 如果是数组 就是多个
            if (Array.isArray(value)) {
                state.fileIsArray = true
                state.fileList = value.map(item => {
                    return {
                        name: item.imageUrl,
                        status: 'done',
                        url: item.imageUrl,
                    }
                })
            } else {
                state.fileIsArray = false
                // 字符串就是单个
                state.fileList = [{
                    name: value,
                    status: 'done',
                    url: value,
                }]
            }

        }
    }, {
    immediate: true
}
)
// 上传前座验证
const beforeUpload = async (file) => {
    console.log(file, 'beforeUpload');
    if (!file.type.includes('image')) {
        message.warning('上传文件只能是图片')
        return false || Upload.LIST_IGNORE;
    }
    if (props.imgSizeType == 1) {
        const isLt2M = file.size / 1024 < props.maxSize
        if (!isLt2M) {
            message.warning('上传文件大小超过限制!')
        }
        return isLt2M || Upload.LIST_IGNORE;
    }
    let limit = await limitFileWH(file);
    return limit|| Upload.LIST_IGNORE;
    // if(props.imgSizeType == 2){
    //     const isLt2M = file.size / 1024 < 300
    //     if (!isLt2M) {
    //         message.warning('上传文件大小不能超过 300KB!')
    //     } 
    //     let limit =await limitFileWH(300,300,file);
    //     return (isLt2M && limit) || Upload.LIST_IGNORE;
    // }
}

const limitFileWH = (file) => {
    // let _this = this;
    let imgWidth = "";
    let imgHight = "";
    const isSize = new Promise(function (resolve, reject) {
        let minWidth = props.minWidth;
        let minHeight = props.minHeight;
        let strictWidth = props.strictWidth;
        let strictHeight = props.strictHeight;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function () {
            imgWidth = img.width;
            imgHight = img.height;
            let valid = true;
            if (strictWidth && strictHeight) {
                valid = img.width == strictWidth && img.height == strictHeight;
            } else if (minWidth && minHeight) {
                valid = img.width >= minWidth && img.height >= minHeight;
            }
            valid ? resolve() : reject();

        }
        img.src = _URL.createObjectURL(file);
    }).then(() => {
        return true;
    },
        () => {
            message.error('请上传符合要求的图片。当前上传图片为：' + imgWidth + 'px*' + imgHight + 'px')
            return false;
        });
    return isSize
}
// 自定义上传  图片
const customRequest = (file) => {
    // console.log(33333,file);
    if (file.file) {
        let formData = new FormData();
        console.log(file,'file.file');
        
        formData.append("file", file.file);
        formData.append("type", 1);  //1：图片，2：视频
        fileUpload(formData).then(res => {
            if (res.status == "000_0000_0000") {
                file.onSuccess();
                state.fileList[state.fileList.length - 1].url = res.result;
                // emit('change', state.fileList)
                if (state.fileIsArray) {
                    let aa = state.fileList.map(item => {
                        return item.url
                    })
                    emit('change', aa)
                } else {
                    emit('change', state.fileList[0].url)
                }

            } else {
                file.onError();
                // state.fileList = []
            }
        })
    }
}
const handleChangeImport = (file) => {
    // console.log(file,'handleChangeImport');
    // console.log(state.fileList,'handleChangeImport2');
    // emit('change',state.fileList)
    // let formdata = new FormData()
    // formdata.append("file", file.file.originFileObj)
    // formdata.append("catalog", '1')
    if (file.file.status === "removed") {

        // formState.imgUrl = formState.imgUrl.filter(item => item != file.file.url)
        // emit('change', state.fileList.map(item => {
        //                 return item.url
        //             }))
        if (state.fileIsArray) {
            let aa = state.fileList.map(item => {
                return item.url
            })
            emit('change', aa)
        } else {
            emit('change', state.fileList[0] ? state.fileList[0].url : '')
        }

    }
    // if (file.file.status === "done") {

    // } else if (file.file.status === "removed") {
    //     formState.imageUrl = formState.imageUrl.filter(item => item.compressPath != file.file.url)
    // } else if (file.file.status === "error") {
    //     file.fileList.splice(file.fileList.length-1,1);
    // }
}
//图片预览
const handlePreview = async file => {
    if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
    }
    state.previewImage = file.url || file.preview;
    state.previewVisible = true;
};
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
</script>

<style lang="less" scoped>
.uptile {
    font-size: 14px;
    color: #999999;
}
</style>